<template>
  <div class="my-component">
    <div class="rankListPage">
      <h1 class="title">图书馆自习室</h1>

      <!-- 模态框 -->
      <div class="modal" v-if="showCancel">
        <div class="modal-content">
          <p v-if="error">{{ error }}</p>
          <!-- 显示错误消息 -->
          <p v-else>取消预约吗？</p>
          <!-- 显示成功消息 -->
          <button @click="closeCancelModal">确认</button>
          <button @click="closeModal">关闭</button>
        </div>
      </div>
      <!-- 模态框 -->
      <div class="modal" v-if="showreconfirm">
        <div class="modal-content">
          <p>当前位置可能有人，确认预约吗？</p>
          <button @click="confirmReservation = true; closeModal()">确认</button>
          <button @click="closeModal">取消</button>
        </div>
      </div>
      <div v-if="step == 1">
        <!-- 时间段选择的模态框 -->
        <div class="time-slot-modal" v-if="showTimeSlotModal">
          <div class="modal-content">
            <h2>选择预约日期</h2>
            <div class="seat-buttons dateitem">
              <button
                v-for="item in dateList"
                :key="item"
                :class="[
                  'time-slot-button',
                  curselectedDateSlot === item ? 'curChoose' : '',
                ]"
                @click="selectDay(item)"
              >
                {{ dateFilter(item) }}
              </button>
            </div>
            <button @click="curselectedDateSlot ? step = 2 : null" class="nextbtn">下一步</button>
          </div>
        </div>
      </div>
      <div v-else-if="step == 2">
        <!-- 时间段选择的模态框 -->
        <div class="time-slot-modal" v-if="showTimeSlotModal">
          <div class="modal-content" style="position: relative">
            <div class="arrow-left-box">
              <div
                class="arrow-left"
                @click="step = 1;selectedTimeSlot = '';"
              ></div>
            </div>
            <h2>选择时间段</h2>
            <p> {{ selectedDateSlot }} -</p>
            <div class="seat-buttons dateitem">
              <button
                v-for="timeSlot in timeSlots"
                :key="timeSlot.id"
                class="time-slot-button"
                :class="{
                  'selected-time-slot': selectedTimeSlot === timeSlot.id,
                }"
                @click="selectTimeSlot(timeSlot.id)"
              >
                {{ timeSlot.label }}
              </button>
            </div>
            <div class="btnbox">
              <button @click="cancelTimeSlot">取消</button>
              <button
                :style="{ opacity: selectedTimeSlot == null ? '0.3' : '1' }"
                @click="confirmTimeSlot"
                :disabled="selectedTimeSlot === null"
              >
                确认
              </button>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="step == 3">    
        <div class="seat-selector">
          <div class="arrow-left-box">
            <div
              class="arrow-left"
              @click="step = 2;showTimeSlotModal = true;"
            ></div>
            <div  class="date-time-container">
              <!-- 显示选择的时间段 -->
              <p>日期:{{ selectedDateSlot}}</p>
              <p>&nbsp;&nbsp;&nbsp;
                时间段: {{ selectedTimeSlot ? timeSlots.find(slot => slot.id === selectedTimeSlot).label : '未选择' }}
              </p>
            </div>
          </div>

          <!-- 'selected-seat': seat[index + 1], 'have-seat': !seat[index + 1] && portseatstatus[index + 1] === 1
                逻辑调整，预约了的显示红色，没被预约的根据portseatstatus来判断显示蓝色 -->
          <button
            v-for="(seat, index) in seatList"
            :key="index"
            class="seat-button"
            :class="{ 'selected-seat': seat[index + 1], 'have-seat': !seat[index + 1] && portseatstatus[index + 1] === 1 }"
            @click="selectSeat(index)"
          >
            座位{{ index + 1 }}
          </button>
        </div>
      </div>
      <div v-else-if="step == 4">
        <div class="seat-selector">
          <div class="arrow-left-box">
            <div @click="resetChoose" style="cursor: pointer">选择时间段</div>
          </div>

          <button
            v-for="(seat, index) in seatList2"
            :key="index"
            class="seat-button"
            @click="showMessageFun('请先选择时间段')"
          >
            座位{{ index + 1 }}
          </button>
        </div>
      </div>

      <div class="tips" v-if="showMsg">
        <div class="messagetext">
          {{ message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import { ref, onMounted } from "vue";
import { useStore } from "vuex";
export default {
  name: "RanklistIndexView",
  setup() {
    const store = useStore();
    let seatId = ref();
    let error = ref(""); // 添加一个用于保存错误信息的变量
    let seatStatusList = ref([]); // 存储座位状态的整数列表
    let portseatstatus = ref([]); // 存储传感器传来的座位状态

    // 获取传感器状态
    const getPortStatus = () => {
      $.post("http://127.0.0.1:3000/user/account/portseatstatus/", (data) => {
        // 更新座位状态
        portseatstatus.value = data;
        // console.log(portseatstatus.value);
      });
    };

    onMounted(() => {
      // 页面加载后立即获取传感器座位状态
      getPortStatus();

      // 设置定时器，每隔一段时间获取座位状态
      setInterval(() => {
        getPortStatus();
      }, 6000);
    });

    //获取当前登录的用户名
    const getCurrentUser = () => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/currentUser", // 后端提供的获取当前登录用户信息的接口
        type: "GET",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        dataType: "json",
        success: function (data) {
          // 在这里处理获取到的用户信息
          console.log("当前登录用户信息：", data.username);
        },
        error: function (xhr, status, error) {
          console.error("获取当前登录用户信息失败", error);
        },
      });
    };

    // 在需要获取当前用户信息的地方调用这个函数
    getCurrentUser();

    return {
      seatStatusList: seatStatusList, // 存储座位状态的整数列表
      seatId,
      error, // 将error变量暴露出去以在模板中显示错误信息
      portseatstatus: portseatstatus,  // 传感器传来的数据
    };
  },

  data() {
    return {
      seatList2: [
        {1:false},{2:false},{3:false},{4:false},{5:false},
        {6:false},{7:false},{8:false},{9:false},{10:false},
        {11:false},{12:false},{13:false},{14:false},{15:false},
        {16:false},{17:false},{18:false},{19:false},{20:false},
        {21:false},{22:false},{23:false},{24:false},{25:false},
      ],
      showMsg: false,
      message: "",
      seatList: [],
      curselectedDateSlot: "",
      selectedDateSlot: "",
      step: 1,
      timeSlots: [
        { id: 1, label: "07:00~09:00" },
        { id: 2, label: "09:10~11:10" },
        { id: 3, label: "11:20~13:20" },
        { id: 4, label: "13:30~15:30" },
        { id: 5, label: "15:40~17:40" },
        { id: 6, label: "17:50~19:50" },
        { id: 7, label: "20:00~23:00" },
      ], //设置可以选择的时间段
      selectedTimeSlot: null, //选取的时间段
      seatOptions: [],
      selectedSeat: null,
      showCancel: false,  // 提示模态框，取消预约
      showreconfirm: false,  // 提示模态框，蓝色座位预约
      confirmReservation: false,  // 蓝色座位，是否确认预约
      showTimeSlotModal: true, // 控制时间段选择弹窗的显示状态
    };
  },
  computed: {
    dateList() {
      const currentDate = new Date();
      const today = currentDate.toLocaleDateString();
      const tomorrow = new Date(currentDate);
      tomorrow.setDate(currentDate.getDate() + 1);
      const twoDaysLater = new Date(currentDate);
      twoDaysLater.setDate(currentDate.getDate() + 2);
      return [today, tomorrow, twoDaysLater];
    },
  },
  created() {
    for (let row = 1; row <= 5; row++) {
      for (let col = 1; col <= 5; col++) {
        const seatNumber = (row - 1) * 5 + col;
        const status = this.seatStatusList[seatNumber - 1];
        // console.log("status", status);
        this.seatOptions.push({
          id: seatNumber,
          label: `座位${seatNumber}`,
          status: status,
          selectedTimeSlot: null, // 添加时间段属性
        });
      }
    }
  },
  methods: {
    //提示信息
    showMessageFun(msg = "", time = 3000) {
      let that = this;
      that.message = msg;
      that.showMsg = true;
      setTimeout(function () {
        that.showMsg = false;
      }, time);
    },


    //选择第几天
    selectDay(item) {
      this.curselectedDateSlot = item;
      this.selectedDateSlot = this.dateFilter(item);
      console.log(this.selectedDateSlot);
    },
    //格式化日期
    dateFilter(v) {
      let date = new Date(v);
      let year = date.getFullYear(); // 年
      let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月
      let day = date.getDate().toString().padStart(2, '0'); // 日
      var str = year + "-" + month + "-" + day;
      return str;
    },
    //选择座位
    selectSeat(index) {
      this.seatId = index + 1;
      let arr = Object.keys(this.seatList[index]);
      if(this.selectedTimeSlot ==null)
      {
        this.showMessageFun("请先选择时间段");
        return;
      }
      // 检查传感器座位状态
      // 逻辑：未被预约且当前位置有人
      if (this.portseatstatus[index + 1] === 1 && !this.seatList[index][arr[0]]) {
        // 座位有人，显示模态框
        this.showreconfirm = true;
      }
      // 没人，正常预约
      else{
        if (!this.seatList[index][arr[0]]) {
          this.getseatDue(); //预约
        } else {
          // this.getseatUnDue(); //取消预约
          this.showCancel = true;
        }
      }
    },
    //某天某个时间段内所有座位的预约情况
    getseatstatus() {
      let that = this;
      // const store = useStore();
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/getseatstatus/",
        type: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log("某天某个时间段内所有座位的预约情况", resp);
          that.seatList = resp;
          console.log("jiekou fanhuifuzhi", that.seatList);
        },
        error: function (xhr, status, error) {
          console.error("发生错误:", error);
        },
      });
    },
    //预约接口
    getseatDue() {
      const that = this;
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/seatDue/",
        type: "post",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          labelId: this.seatId,
          seatId: this.seatId,
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log(resp);
          that.showMessageFun(resp.message); //提示信息弹窗
          that.getseatstatus(); //重新获取座位
        },
      });
    },
    //取消预约
    getseatUnDue() {
      const that = this;
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/seatUnDue/",
        type: "delete",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.token,
        },
        data: {
          seatId: this.seatId,
          selectedDateSlot: this.selectedDateSlot,
          selectedTimeSlot: this.timeSlots[this.selectedTimeSlot - 1].label,
        },
        success(resp) {
          console.log(resp);
          that.showMessageFun(resp.message); //提示信息弹窗
          that.getseatstatus(); //重新获取座位
        },
      });
    },
    /*******选择时间段设置******/
    /*******当前时间前的时间段无法进行预约*****/
    selectTimeSlot(timeSlotId) {
      const selectedTimeSlot = this.timeSlots.find(slot => slot.id === timeSlotId);
       console.log(selectedTimeSlot.label);
      // 提取开始时间和结束时间
      const [startTime, endTime] = selectedTimeSlot.label.split('~').map(time => time.trim());
      // 构建开始时间的 Date 对象
      new Date(`${this.selectedDateSlot} ${startTime}`);  // 获取时间段开始的时间//未使用
      // 构建结束时间的 Date 对象
      const endDate = new Date(`${this.selectedDateSlot} ${endTime}`);
      // 检查选择的时间段是否在当前系统时间之前
      const currentTime = new Date();
      if (endDate <= currentTime) {
        // 如果选择的时间在当前系统时间之前，不执行任何操作
        this.showMessageFun('选择的时间段在当前时间之前，请重新选择');
        return;
      }
      // 如果选择的时间在当前系统时间之后，则执行相应操作
      this.selectedTimeSlot = timeSlotId;
    },
    
    confirmTimeSlot() {
      if (this.selectedTimeSlot == null) {
        return;
      }
      this.step = 3;
      this.getseatstatus();
    },
    cancelTimeSlot() {
      if (this.seatList.length > 0) {
        this.step = 3;
      } else {
        this.step = 4;
      }
      this.closeTimeSlotModal();
    },
    resetChoose() {
      this.step = 1;
      this.showTimeSlotModal = true;
      this.curselectedDateSlot = "";
      this.selectedTimeSlot = "";
    },
    closeTimeSlotModal() {
      this.showTimeSlotModal = false;
      this.selectedSeat = null; // 清除选中座位
      this.selectedTimeSlot = null; // 清除选中时间段
    },

    closeModal() {
      this.showCancel = false;
      this.selectedSeat = null; // 清除选中座位

      // 蓝色座位提示是否预约逻辑
      this.showreconfirm = false;
      if (this.confirmReservation) {
        // 用户点击确认，进行预约操作
        this.getseatDue();
      } else {
        // 用户点击取消，不进行预约操作
        // 可以在这里添加取消预约的逻辑
      }

      this.confirmReservation = false; // 重置变量
    },
    // 确认取消预约
    closeCancelModal(){
      this.showCancel = false;
      this.getseatUnDue();
      this.selectedSeat = null; // 清除选中座位
    },
  },
};
</script>

<style scoped>
/*10.25杨灿修改 */
.my-component  {
  background-image: url('@/assets/images/image4.jpg');
  background-size: 100% 100%; 
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
   position: absolute; 
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

}

.arrow-left-box {
  position: absolute;
  left: 24px;
  top: 30px;
  color: #4caf50;
}
.arrow-left {
  position: absolute;
  cursor: pointer;
}
.arrow-left:before,
.arrow-left:after {
  position: absolute;
  content: "";
  border-top: 10px transparent dashed;
  border-left: 10px transparent dashed;
  border-bottom: 10px transparent dashed;
  border-right: 10px #ffffff solid;
}
.arrow-left:before {
  border-right: 10px #979797 solid;
}
.arrow-left:after {
  left: 2px; /*覆盖并错开1px*/
  border-right: 10px #ffffff solid;
}
.tips {
  position: fixed;
  top: 60px;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.messagetext {
  display: inline-block;
  height: 40px;
  line-height: 40px;
  background: rgba(0, 0, 0, 0.6);
  padding: 0 60px;
  font-size: 18px;
  border-radius: 5px;
  color: #ffffff;
  box-shadow: 0px 0px 3px 2px rgba(0, 0, 0, 0.12);
}
.title {
  position: fixed;
  left: 50%;
  transform: translate(-50%, -50%);
  top: 20%;
}
.nextbtn {
  height: 40px;
  line-height: 40px;
  margin-top: 10px;
}
.seat-selector {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 70px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.date-time-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-left: 100px;
  /* 其他样式 */
 }
.seat-button {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  border-radius: 50%;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.seat-button:hover {
  background-color: #ccc;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  /* 确保模态框在其他元素之上 */
}

.modal-content {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  /* 添加阴影效果 */
  max-width: 422px;
  /* 控制模态框的最大宽度 */
  width: 90%;
  /* 控制模态框的宽度 */
}

/* 关闭按钮样式 */
.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 18px;
  color: #777;
}

.close-button:hover {
  color: #333;
}

/* 新增样式用于选中座位的按钮 */
.selected-seat {
  background-color: red;
  color: white;
}
/*座位有人，样式为蓝色*/
.have-seat {
  background-color: blue; /* 根据需要更改颜色 */
  color: white;
}

/*******************************/
/*时间段*/
.seat-buttons {
  display: flex;
  flex-wrap: wrap;
}
.curChoose {
  background: #4caf50 !important;
  color: #ffffff;
}
.dateitem button:hover {
  cursor: pointer;
  background: #4caf50;
  color: #ffffff;
}
.btnbox {
  display: flex;
  justify-content: space-between;
  height: 38px;
  line-height: 36px;
  margin-top: 10px;
  overflow: hidden;
}
.btnbox button {
  width: 40%;
  color: #000;
  border: 1px solid #000;
}
.time-slot-button {
  margin: 5px;
  padding: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.selected-time-slot {
  background-color: #4caf50;
  color: white;
}

.time-slot-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}


/********手机端样式*********/

/* 可根据需要自定义模态框的样式 */
@media (max-width: 600px) {
  .modal-content {
    max-width: 80%; /* 或其他适当的值 */
    /* 其他样式调整 */
  }
  .seat-selector {
    padding: 71px; /* 或其他适当的值 */
    flex-wrap: wrap; /* 添加弹性布局以适应小屏幕 */
    width: 96%;
    height: 63%;
    /* 其他样式调整 */
  }

  .date-time-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-left: 80px;
    /* 其他样式 */
    position: fixed;
    top: 25px;
    left: -25px;
   }
   .seat-button {
    width: 34px;
    height: 31px;
    font-size: 9px;
    border: 1px solid #000;
    border-radius: 50%;
    margin: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
  .arrow-left-box {
    position: absolute;
    left: 24px;
    top: 80px;
    color: #4caf50;
  }

  /*显示提示信息格式调整*/
  .messagetext {
    font-size: 14px; /* 根据需要调整字体大小 */
    padding: 0 20px; /* 根据需要调整内边距 */
  }
}
</style>